// pages/profile/reservation_detail.js
import api from '../../utils/api'
const app = getApp()

const STATUS_MAP = {
  '0': { text: '待审核', cls: 'pending' },
  '1': { text: '已确认', cls: 'confirmed' },
  '2': { text: '已取消', cls: 'canceled' },
  '3': { text: '已拒绝', cls: 'rejected' },
  // 兼容英文字段
  pending: { text: '待审核', cls: 'pending' },
  approved: { text: '已确认', cls: 'confirmed' },
  confirmed: { text: '已确认', cls: 'confirmed' },
  cancelled: { text: '已取消', cls: 'canceled' },
  canceled: { text: '已取消', cls: 'canceled' },
  rejected: { text: '已拒绝', cls: 'rejected' }
}

Page({
  data: {
    loading: true,
    id: '',
    detail: null,
    statusText: '',
    statusClass: '',
    qrcodeUrl: '',
    showQrCode: false,
    visitors: [],
    isValidReservation: false // 是否为有效预约（已确认状态）
  },

  onLoad(options) {
    const id = options.id
    if (!id) {
      wx.showToast({ title: '参数错误', icon: 'none' })
      setTimeout(() => wx.navigateBack(), 1500)
      return
    }
    this.setData({ id })
    this.loadDetail()
  },

  async loadDetail() {
    try {
      this.setData({ loading: true })
      const detail = await api.reservation.getPersonalDetail(this.data.id)

      // 状态与是否有效预约
      const raw = detail.status
      const key = typeof raw === 'number' ? String(raw) : String(raw || '').toLowerCase()
      const statusMap = STATUS_MAP[key] || { text: '未知状态', cls: 'pending' }
      const isValidReservation = key === '1' || key === 'confirmed' || key === 'approved'

      // 访客信息（保持原有逻辑，优先 individual_reservations）
      let visitors = []
      if (Array.isArray(detail.individual_reservations) && detail.individual_reservations.length) {
        visitors = detail.individual_reservations.map(ir => ({
          name: ir.visitor_name || '',
          id_type: ir.visitor_id_type || '',
          id_number: ir.visitor_id_card || '',
          phone: '',
          _idTypeLabel: this.getIdTypeLabel(ir.visitor_id_type)
        }))
      } else if (Array.isArray(detail.visitors) && detail.visitors.length) {
        visitors = detail.visitors.map(v => ({
          ...v,
          _idTypeLabel: this.getIdTypeLabel(v.id_type)
        }))
      } else {
        const fallback = {
          name: detail.contact_name || '',
          phone: detail.contact_phone || '',
          id_type: detail.id_type || '',
          id_number: detail.id_number || ''
        }
        if (fallback.name || fallback.id_number || fallback.phone) {
          visitors = [{ ...fallback, _idTypeLabel: this.getIdTypeLabel(fallback.id_type) }]
        }
      }

      // 主码（备用）
      const primaryCode =
        detail.primary_reservation_code ||
        (Array.isArray(detail.reservation_codes) && detail.reservation_codes[0]) ||
        detail.reservation_code || ''

      // 生成每位游客的二维码 slides
      let qrSlides = []
      if (isValidReservation) {
        if (Array.isArray(detail.individual_reservations) && detail.individual_reservations.length) {
          qrSlides = detail.individual_reservations
            .map(ir => {
              const code = ir.reservation_code || ir.code || ir.qr_code || ir.reservation_no || ''
              if (!code) return null
              const content = `https://nzy.congqian.cn/qr?p=pages/qr/qr?code=${code}`
              const qrcodeUrl = `https://nzy.congqian.cn/api/qrcode.php?text=${encodeURIComponent(content)}`
              return {
                name: ir.visitor_name || '',
                code,
                qrcodeUrl
              }
            })
            .filter(Boolean)
        } 
        // 回退：无 individual_reservations 则用主码生成一个 slide
        if (!qrSlides.length && primaryCode) {
          const content = `https://nzy.congqian.cn/qr?p=pages/qr/qr?code=${primaryCode}`
          const qrcodeUrl = `https://nzy.congqian.cn/api/qrcode.php?text=${encodeURIComponent(content)}`
          const fallbackName = (visitors[0] && visitors[0].name) || detail.contact_name || '预约人'
          qrSlides = [{ name: fallbackName, code: primaryCode, qrcodeUrl }]
        }
      }

      // 保留单码 qrcodeUrl（兼容旧结构，不再用于渲染）
      const qrcodeUrl = ''

      this.setData({
        detail,
        statusText: statusMap.text,
        statusClass: statusMap.cls,
        isValidReservation,
        visitors,
        qrSlides,
        currentSlideIndex: 0,
        qrcodeUrl,
        loading: false
      })

      console.log('预约详情加载完成:', detail)
    } catch (error) {
      console.error('加载预约详情失败:', error)
      wx.showToast({ title: error.message || '加载失败', icon: 'none' })
      this.setData({ loading: false })
      setTimeout(() => wx.navigateBack(), 2000)
    }
  },

  onSwiperChange(e) {
    this.setData({ currentSlideIndex: e.detail.current || 0 })
  },

  // 显示二维码
  showQrCode() {
    const slides = this.data.qrSlides || []
    const idx = this.data.currentSlideIndex || 0
    const url = slides[idx] && slides[idx].qrcodeUrl
    if (!url) {
      wx.showToast({ title: '二维码不可用', icon: 'none' })
      return
    }
    wx.previewImage({
      urls: [url],
      current: url
    })
  },

  // 保存二维码到相册
  async saveQrCode() {
    const slides = this.data.qrSlides || []
    const idx = this.data.currentSlideIndex || 0
    const url = slides[idx] && slides[idx].qrcodeUrl
    if (!url) {
      wx.showToast({ title: '二维码不可用', icon: 'none' })
      return
    }

    try {
      wx.showLoading({ title: '保存中...' })
      const res = await new Promise((resolve, reject) => {
        wx.downloadFile({ url, success: resolve, fail: reject })
      })
      await new Promise((resolve, reject) => {
        wx.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success: resolve, fail: reject })
      })
      wx.hideLoading()
      wx.showToast({ title: '保存成功', icon: 'success' })
    } catch (error) {
      wx.hideLoading()
      console.error('保存二维码失败:', error)
      wx.showToast({ title: '保存失败', icon: 'none' })
    }
  },

  // 取消预约
  async cancelReservation() {
    const detail = this.data.detail || {}
    if (!detail.can_cancel) {
      wx.showToast({ title: '该预约无法取消', icon: 'none' })
      return
    }

    const confirm = await this.confirmAsync('确定取消该预约吗？取消后不可恢复。')
    if (!confirm) return

    try {
      wx.showLoading({ title: '取消中...' })
      await api.reservation.cancelPersonal(this.data.id)
      wx.hideLoading()
      wx.showToast({ title: '取消成功', icon: 'success' })
      setTimeout(() => { wx.navigateBack() }, 1500)
    } catch (error) {
      wx.hideLoading()
      console.error('取消预约失败:', error)
      wx.showToast({ title: error.message || '取消失败', icon: 'none' })
    }
  },

  // 联系客服
  contactService() {
    wx.showModal({
      title: '联系客服',
      content: '如需帮助，请拨打客服电话：025-85811111',
      showCancel: true,
      confirmText: '拨打电话',
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '025-85811111',
            fail: () => {
              wx.showToast({ title: '拨号失败', icon: 'none' })
            }
          })
        }
      }
    })
  },

  confirmAsync(message) {
    return new Promise(resolve => {
      wx.showModal({
        title: '确认操作',
        content: message,
        success(res) { resolve(res.confirm) },
        fail() { resolve(false) }
      })
    })
  }, // 注意：这里需要这个逗号
  getIdTypeLabel(type) {
    if (!type) return '证件'
    const t = String(type).toUpperCase()
    if (t.includes('ID') || t.includes('身份证')) return '身份证'
    if (t.includes('PASSPORT') || t.includes('护照')) return '护照'
    if (t.includes('GAZJ') || t.includes('港澳台') || t.includes('TAIWAN') || t.includes('HK') || t.includes('MO')) return '港澳台居民居住证'
    if (t.includes('MILITARY') || t.includes('军官')) return '军官证'
    return type
  }
})